import axios from 'axios'
import { ElMessage } from 'element-plus';
import router from '../router';

//创建axios实例对象
const request = axios.create({
  baseURL: '/api',
  timeout: 600000,
});

//axios的响应 response 拦截器
request.interceptors.response.use(
  (response) => { //成功回调
    return response.data
  },
  (error) => { //失败回调
    if (error.response.status === 401) {
      //token过期
      ElMessage.error("登录已过期，请重新登录！");
      router.push("/login"); //跳转到登录页
    } else {
      //其他错误
      ElMessage.error("接口访问异常"); //提示错误信息
    }
    return Promise.reject(error)
  }
) 
//axios的请求 request 拦截器
request.interceptors.request.use(
  (config) => { //成功回调
    const loginUser = JSON.parse(localStorage.getItem('user'));
    if (loginUser && loginUser.token) {//获取token
      config.headers.token = loginUser.token; //设置请求头
    }
    return config; //返回配置对象
  }, 
  (error) => { //失败回调
    
    return Promise.reject(error)
  }
)

export default request